<template>
  <view class="bind-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <image src="/static/settings/back.png" mode="widthFix"></image>
      </view>
      <text class="title">账号绑定</text>
    </view>

    <!-- 手机号绑定区域 -->
    <view class="form-section">
      <text class="section-title">手机号绑定</text>
      <!-- 未绑定状态 -->
      <view class="form-group" v-if="!isPhoneBound">
        <text class="label">手机号</text>
        <view class="input-row">
          <input 
            type="number" 
            placeholder="请输入手机号" 
            v-model="phone" 
            @blur="validatePhone"
            class="bind-input"
          />
          <button 
            class="code-btn" 
            :disabled="phoneCountdown > 0 || !isPhoneValid"
            @click="sendPhoneCode"
          >
            {{ phoneCountdown > 0 ? `${phoneCountdown}s后重试` : '获取验证码' }}
          </button>
        </view>
        <text class="error-message" v-if="phoneError">{{ phoneError }}</text>

        <text class="label mt-30">验证码</text>
        <input 
          type="number" 
          placeholder="请输入验证码" 
          v-model="phoneCode" 
          class="bind-input"
        />
      </view>
      <!-- 已绑定状态 -->
      <view class="bound-info" v-else>
        <text class="bound-text">已绑定手机号：{{ boundPhone }}</text>
        <button class="unbind-btn" @click="confirmUnbind('phone')">取消绑定</button>
      </view>
    </view>

    <!-- 邮箱绑定区域 -->
    <view class="form-section">
      <text class="section-title">邮箱绑定</text>
      <!-- 未绑定状态 -->
      <view class="form-group" v-if="!isEmailBound">
        <text class="label">邮箱</text>
        <view class="input-row">
          <input 
            type="text" 
            placeholder="请输入邮箱" 
            v-model="email" 
            @blur="validateEmail"
            class="bind-input"
          />
          <button 
            class="code-btn" 
            :disabled="emailCountdown > 0 || !isEmailValid"
            @click="sendEmailCode"
          >
            {{ emailCountdown > 0 ? `${emailCountdown}s后重试` : '获取验证码' }}
          </button>
        </view>
        <text class="error-message" v-if="emailError">{{ emailError }}</text>

        <text class="label mt-30">验证码</text>
        <input 
          type="text" 
          placeholder="请输入验证码" 
          v-model="emailCode" 
          class="bind-input"
        />
      </view>
      <!-- 已绑定状态 -->
      <view class="bound-info" v-else>
        <text class="bound-text">已绑定邮箱：{{ boundEmail }}</text>
        <button class="unbind-btn" @click="confirmUnbind('email')">取消绑定</button>
      </view>
    </view>

    <!-- 绑定提交按钮 -->
    <button 
      type="primary" 
      class="submit-btn" 
      @click="bindAccount"
      :disabled="!canSubmit"
    >
      绑定账号
    </button>

    <!-- 取消绑定确认弹窗（依赖 uni-popup 组件） -->
    <uni-popup ref="unbindPopup" type="confirm" @confirm="handleUnbind">
      <uni-popup-header title="确认取消绑定" />
      <uni-popup-content>
        确定要取消绑定{{ unbindType === 'phone' ? '手机号' : '邮箱' }}吗？
      </uni-popup-content>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 手机号绑定状态
      phone: '',          // 输入的手机号
      phoneCode: '',      // 手机号验证码
      phoneError: '',     // 手机号错误提示
      phoneCountdown: 0,  // 手机号验证码倒计时
      isPhoneValid: false,// 手机号格式是否有效
      isPhoneBound: false,// 是否已绑定手机号
      boundPhone: '138****1234', // 模拟已绑定的手机号

      // 邮箱绑定状态
      email: '',          // 输入的邮箱
      emailCode: '',      // 邮箱验证码
      emailError: '',     // 邮箱错误提示
      emailCountdown: 0,  // 邮箱验证码倒计时
      isEmailValid: false,// 邮箱格式是否有效
      isEmailBound: false,// 是否已绑定邮箱
      boundEmail: 'example@mail.com', // 模拟已绑定的邮箱

      // 弹窗控制
      unbindType: '',     // 取消绑定的类型（phone/email）
    }
  },
  computed: {
    // 判断是否可提交绑定
    canSubmit() {
      if (this.isPhoneBound && this.isEmailBound) return true; // 已全绑定
      if (!this.isPhoneBound && !this.isEmailBound) {         // 都未绑定
        return this.isPhoneValid && this.phoneCode && this.isEmailValid && this.emailCode;
      }
      if (!this.isPhoneBound) {                               // 仅手机号未绑定
        return this.isPhoneValid && this.phoneCode;
      }
      if (!this.isEmailBound) {                               // 仅邮箱未绑定
        return this.isEmailValid && this.emailCode;
      }
      return false;
    }
  },
  methods: {
    // 返回上一级页面
    goBack() {
      uni.navigateBack();
    },

    // 验证手机号格式
    validatePhone() {
      const reg = /^1[3-9]\d{9}$/;
      if (!this.phone) {
        this.phoneError = '请输入手机号';
        this.isPhoneValid = false;
      } else if (!reg.test(this.phone)) {
        this.phoneError = '手机号格式不正确';
        this.isPhoneValid = false;
      } else {
        this.phoneError = '';
        this.isPhoneValid = true;
      }
    },

    // 发送手机号验证码（模拟）
    sendPhoneCode() {
      if (this.phoneCountdown > 0) return; // 倒计时中不重复发送
      this.validatePhone();                // 先验证格式
      if (this.isPhoneValid) {
        this.phoneCountdown = 60;          // 启动60秒倒计时
        const timer = setInterval(() => {
          this.phoneCountdown--;
          if (this.phoneCountdown <= 0) clearInterval(timer);
        }, 1000);
        uni.showToast({ title: '验证码已发送', icon: 'success' });
      }
    },

    // 验证邮箱格式
    validateEmail() {
      const reg = /^[\w.-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
      if (!this.email) {
        this.emailError = '请输入邮箱';
        this.isEmailValid = false;
      } else if (!reg.test(this.email)) {
        this.emailError = '邮箱格式不正确';
        this.isEmailValid = false;
      } else {
        this.emailError = '';
        this.isEmailValid = true;
      }
    },

    // 发送邮箱验证码（模拟）
    sendEmailCode() {
      if (this.emailCountdown > 0) return; // 倒计时中不重复发送
      this.validateEmail();                // 先验证格式
      if (this.isEmailValid) {
        this.emailCountdown = 60;          // 启动60秒倒计时
        const timer = setInterval(() => {
          this.emailCountdown--;
          if (this.emailCountdown <= 0) clearInterval(timer);
        }, 1000);
        uni.showToast({ title: '验证码已发送', icon: 'success' });
      }
    },

    // 绑定账号（模拟）
    bindAccount() {
      if (!this.canSubmit) return; // 校验不通过则不提交
      uni.showLoading({ title: '绑定中...' });
      setTimeout(() => {
        uni.hideLoading();
        // 模拟绑定成功，更新状态
        if (!this.isPhoneBound) {
          this.isPhoneBound = true;
          this.boundPhone = this.phone;
          this.phone = '';
          this.phoneCode = '';
        }
        if (!this.isEmailBound) {
          this.isEmailBound = true;
          this.boundEmail = this.email;
          this.email = '';
          this.emailCode = '';
        }
        uni.showToast({ title: '绑定成功', icon: 'success' });
      }, 1500);
    },

    // 打开取消绑定确认弹窗
    confirmUnbind(type) {
      this.unbindType = type;
      this.$refs.unbindPopup.open();
    },

    // 处理取消绑定逻辑
    handleUnbind() {
      if (this.unbindType === 'phone') {
        this.isPhoneBound = false;
        this.boundPhone = '';
      } else {
        this.isEmailBound = false;
        this.boundEmail = '';
      }
      uni.showToast({ title: '取消绑定成功', icon: 'success' });
    }
  }
}
</script>

<style scoped>
/* 基础样式变量 */
:root {
  --primary-color: #42b983;   /* 主色调 */
  --error-color: #f56c6c;     /* 错误色 */
  --text-color: #333;         /* 主文本色 */
  --text-light-color: #666;   /* 辅助文本色 */
  --border-color: #ddd;       /* 边框色 */
  --bg-color: #f5f5f5;        /* 背景色 */
}

/* 页面容器 */
.bind-container {
  background-color: var(--bg-color);
  min-height: 100vh;
}

/* 顶部导航 */
.header {
  height: 100rpx;
  background-color: var(--primary-color);
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  position: relative;
}
.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  left: 30rpx;
  top: 50%;
  transform: translateY(-50%);
}
.back-btn image {
  width: 24rpx;
  height: 40rpx;
}
.title {
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  width: 100%;
}

/* 表单区块 */
.form-section {
  background-color: #fff;
  margin: 30rpx;
  padding: 30rpx;
  border-radius: 16rpx;
}
.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: var(--text-color);
  margin-bottom: 20rpx;
}
.form-group {
  margin-bottom: 30rpx;
}
.label {
  display: block;
  font-size: 28rpx;
  color: var(--text-light-color);
  margin-bottom: 10rpx;
}
.mt-30 {
  margin-top: 30rpx;
}

/* 输入行（输入框 + 验证码按钮） */
.input-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.bind-input {
  flex: 1;
  height: 80rpx;
  border: 1rpx solid var(--border-color);
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
}
.bind-input:focus {
  border-color: var(--primary-color); /* 焦点时高亮 */
}

/* 验证码按钮 */
.code-btn {
  width: 200rpx;
  height: 80rpx;
  background-color: var(--primary-color);
  color: #fff;
  font-size: 26rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.code-btn[disabled] {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 错误提示 */
.error-message {
  font-size: 24rpx;
  color: var(--error-color);
  margin-top: 10rpx;
}

/* 已绑定信息 */
.bound-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.bound-text {
  font-size: 28rpx;
  color: var(--text-color);
}
.unbind-btn {
  background-color: var(--error-color);
  color: #fff;
  padding: 15rpx 30rpx;
  border-radius: 8rpx;
  font-size: 26rpx;
}

/* 提交按钮 */
.submit-btn {
  margin: 40rpx 30rpx;
  height: 90rpx;
  background-color: var(--primary-color);
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
}
.submit-btn[disabled] {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>